# -*- coding: utf-8 -*-
# @author: Dinh Manh Dau <dinhmanhdau@gmail.com>
import os, datetime, time, traceback, re
import threading
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetRecentPosts, NewPost
from pymongo import Connection

MONGO_SERVER    = '27.0.12.106'   
MONGO_PORT      = 27017
MAX_ARTICLE     = 10
URL             = 'http://wp.mana.vn/xmlrpc.php'
DATABASE        = 'tintuc_v2'
NEWS_COLLECTION = 'article'
start = 0

class Mana():
    def __init__(self, server, port, database):
        CONNECT  = Connection(server, port)
        self.db  = CONNECT[database]
        self.wp  = Client(URL, 'admin', 'wp_@manaTech')
    
    def __del__(self):
        self.wp  = None
    
    def convertToUTF8(self, text):
        try:
            if type(text).__name__ == 'unicode': text = text.encode('utf-8')
            text = unicode(text, 'utf-8')
            return text
        except:
            traceback.print_exc()
            return text
    
    def getRecentNews(self, numNews=10):
        try:
            data = self.wp.call(GetRecentPosts(numNews))
            return data
        except:
            traceback.print_exc()

    def toAscii(self, text):
        ''' Chuyển chuỗi tiếng Việt Unicode tổ hợp về dạng Ascii không dấu '''
        if text == '': return ''
        if type(text).__name__ == 'unicode': text   = text.encode('utf-8')
        listPattern = ["á|à|ả|ạ|ã|â|ấ|ầ|ẩ|ậ|ẫ|ă|ắ|ằ|ẳ|ặ|ẵ", "Á|À|Ả|Ạ|Ã|Â|Ấ|Ầ|Ẩ|Ậ|Ẫ|Ă|Ắ|Ằ|Ẳ|Ặ|Ẵ",
                       "đ", "Đ", "í|ì|ỉ|ị|ĩ", "Í|Ì|Ỉ|Ị|Ĩ", "é|è|ẻ|ẹ|ẽ|ê|ế|ề|ể|ệ|ễ", "É|È|Ẻ|Ẹ|Ẽ|Ê|Ế|Ề|Ể|Ệ|Ễ",
                       "ó|ò|ỏ|ọ|õ|ô|ố|ồ|ổ|ộ|ỗ|ơ|ớ|ờ|ở|ợ|ỡ", "Ó|Ò|Ỏ|Ọ|Õ|Ô|Ố|Ồ|Ổ|Ộ|Ỗ|Ơ|Ớ|Ờ|Ở|Ợ|Ỡ",
                       "ú|ù|ủ|ụ|ũ|ư|ứ|ừ|ử|ự|ữ", "Ú|Ù|Ủ|Ụ|Ũ|Ư|Ứ|Ừ|Ử|Ự|Ữ", "ý|ỳ|ỷ|ỵ|ỹ", "Ý|Ỳ|Ỷ|Ỵ|Ỹ"]
        rep = ['a', 'A', 'd', 'D', 'i', 'I', 'e', 'E', 'o', 'O', 'u', 'U', 'y', 'Y']
        for idx in range(len(listPattern)):
            text = re.sub(listPattern[idx], rep[idx], text)
        return text

    def postNews(self, row):
        try:
            post            = WordPressPost()
            post.title      = self.convertToUTF8(row['title'])
            post.categories = [unicode('Tin tức', 'utf-8'),]
            print 'Title: ', self.toAscii(post.title), self.toAscii(row['newsLink'])
            text = ''
            text += '<div id="article_desc">' + self.convertToUTF8(row['description']) + '</div><br />'
            for item in row['content']:
                data = self.convertToUTF8(item['data'])
                if item['type']=='image':
                    img_text = '<img src="' + 'http://pn.mana.vn' + data + '" />'
                    text += '<div align="center">'+ img_text + '</div>'
                    if len(item['caption'])>0:
                        text += '<div align="center" id="caption_img">' + self.convertToUTF8(item['caption']) + '</div>'
                elif item['type'] == 'textbold':
                    text += '<div id="textbold">' + data + '</div>'
                else:
                    text += '<div id="text">' + data + '</div>'
                text += '<br />'
            #print 'Text: ', text
            post.description = text
            idPost  = self.wp.call(NewPost(post, True))
            return idPost
        except:
            traceback.print_exc()

    def getHotNews(self, numRows=10):
        try:
            data = []
            collectionA  = self.db[NEWS_COLLECTION]
            tmp          = self.getRecentNews()
            for item in tmp:   data.append(item.title)
            rows         = collectionA.find({'is_active': True}).sort('update', -1).limit(numRows)
            for row in rows:
                if row['title'] not in data:
                    idPost = self.postNews(row)
                    if idPost==None and idPost<=0:
                        print 'Có lỗi xảy ra trong quá trình lưu.'
                    else:
                        print 'Lưu thành công.'
                else: 
                    print 'Đã tồn tại trong cơ sỡ dữ liệu.'
        except:
            traceback.print_exc()
    
def timeOut():        
    while True:
        delta = time.time() - start
        if delta > 300:
            print 'Dừng chương trình vì vượt quá thời gian chạy.', datetime.datetime.now()
            pid = os.getpid(); os._exit(1); os.kill(pid, 9)
        time.sleep(30)

if __name__ == '__main__':
    try:
        print 'start post article to mana.vn'
        start = time.time() 
        timeout = threading.Thread(target=timeOut).start()
        mana = Mana(MONGO_SERVER, MONGO_PORT, DATABASE)
        mana.getHotNews(10)
        print 'Finished.', datetime.datetime.now()
        os._exit(1); os.kill(os.getpid(), 9)
    except:
        traceback.print_exc()
